
// Result 链式写法

use std::fs::File;
use std::io::Read;

fn read_file() -> Result<String, String> {
    File::open("foo.txt")
        .map_err(|e| format!("couldn't open file: {}", e))
        .and_then(|mut file| {
            let mut contents = String::new();
            file.read_to_string(&mut contents)
                .map_err(|e| format!("couldn't read file: {}", e))
                .map(|_| contents)
        })
    
    // 不产生Err,and_then才会执行
}

fn main() {
    // match read_file() {
    //     Ok(s) => {
    //         println!("{}", s);
    //     }
    //     Err(err) => {
    //         println!("Error: {}", err);
    //     }
    // }

    read_file().map_err(|e| println!("{}", e))
        .and_then(|s| println!("{}", s))
}